package com.ele.server.dao;

import com.ele.model.Section;
import com.ele.shared.dto.grid.SectionGridRow;

import java.util.ArrayList;
import java.util.List;

public class SectionDAO extends GenericDAO<Section> {

    public SectionDAO() {
        super(Section.class);
    }

    public List<SectionGridRow> getGridData() {
        List<Object[]> list = em.createQuery("SELECT e.id, e.name FROM " + clazz.getSimpleName() + " e").getResultList();

        List<SectionGridRow> rows = new ArrayList<SectionGridRow>(list.size());
        for (Object[] objects : list) {
            Long id = (Long) objects[0];
            String name = (String) objects[1];
            rows.add(new SectionGridRow(id, name));
        }

        return rows;
    }

    public Section getCurrentSection(Long userId) {
        List resultList = em.createNativeQuery(("SELECT * FROM section s" +
                " JOIN question q ON q.SECTION_ID = s.ID" +
                " JOIN answer a ON a.QUESTION_ID = q.ID" +
                " LEFT JOIN questionusage u ON u.QUESTION_ID = q.ID AND u.USER_ID = :userId" +
                " WHERE u.id IS NULL OR u.completed IS FALSE" +
                " GROUP BY s.id LIMIT 1").replaceFirst(":userId", String.valueOf(userId)), Section.class)
                .getResultList();

        if (resultList.isEmpty()) {
            return null;
        } else {
            return serialize((Section) resultList.get(0));
        }
    }
}
